<template>
  <div >
    <a-cascader :value="defaultValue"
                :options="areaList"
                :fieldNames="{label:'name',value:'id',children:'children'}"
                :placeholder="title"
                :showSearch="search"
                :expandTrigger="expandTrigger"
                :changeOnSelect="changeOnSelect"
                notFoundContent="暂无数据"
                @change="onChange"
                :style="{width: width}"
    />
  </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  import { UI_CACHE_SYS_AREA } from "@/store/mutation-types"
  import Vue from 'vue'

  export default {
    name: 'JAreaSys',
    props: {
      value: {
        type: String,
        required:false
      },
      width: {
        type: String,
        default: '100%'
      },
      //联机下拉深度
      level: {
        type: Number,
        required: false,
        default: 3,
      },
      //当此项为 true 时，点选每级菜单选项值都会发生变化
      changeOnSelect: {
        type: Boolean,
        required: false,
        default: false,
      },
      //在选择框中显示搜索框
      search: {
        type: Boolean,
        required: false,
        default: false,
      },
      //在选择框中显示搜索框
      title: {
        type: String,
        required: false,
        default: '请选择',
      },
      //是否是查询
      query: {
        type: Boolean,
        required: false,
        default: false,
      },

      //展开形式  点击 和 悬浮
      click: {
        type: Boolean,
        required: false,
        default: true,
      },

    },
    data() {
      return {
        expandTrigger:'check',
        defaultValue: [],
        areaList:[],
      }
    },

    watch: {
      value: {
        immediate: true,
        handler(val) {
          if(val){
            val = this.removeStr(val,"*");
            this.defaultValue = this.trimSpace(val.split(","));
          }else{
            this.defaultValue = [];
          }
        },
        //立刻执行handler
        immediate: true
      },
      level: {
        immediate: true,
        handler(val) {
          //console.log("level--"+val)
        },
        //立刻执行handler
        immediate: true
      },
      click: {
        immediate: true,
        handler(val) {
           this.expandTrigger= val?'click':"hover";
        },
        //立刻执行handler
        immediate: true
      },
    },
    created() {
      this.initAreaData();
    },
    methods: {
      onChange(value) {
        if(value && value.length>0){
          if(!this.query){
            this.$emit('change', value.join(","));//v-model 赋值
          }else{
            //v-model 多选字段模糊查询
            // 赋值现在name传入值 ,a,b,c, 那么结果sql就是 name like '%a%' or name like '%b%' or name like '%c%'
            //this.$emit('change', ','+value.join(",")+",");
            this.$emit('change', '*'+value.join(",")+"*");
          }
        }else{
          this.$emit('change', '');//v-model 赋值
        }
      },

      initAreaData(){
        if (Vue.ls.get(UI_CACHE_SYS_AREA)) {
          let list =  JSON.parse(Vue.ls.get(UI_CACHE_SYS_AREA));
          this.areaList = this.recursiveFilter(list)
        }else{
          getAction(`${window._CONFIG['domianURL']}/sysArea/treeNodes`,{type:1}).then((res)=>{
            if(res.success){
              list = res.result;
              this.areaList = this.recursiveFilter(list)
              Vue.ls.remove(UI_CACHE_SYS_AREA)
              Vue.ls.set(UI_CACHE_SYS_AREA,  JSON.stringify(list), 7 * 24 * 60 * 60 * 1000)
            }
          })
        }
      },
      /**
       * 递归过滤嵌套数组（树形结构）
       * @param arr {Array}要过滤的原始数据
       * @param type {Boolean} 你要过滤的关键词
       *
       */
      recursiveFilter(arr){
        let that = this;
        let data = arr.filter(item=> item.level < this.level).map((item)=>{
          item=Object.assign({},item)
          if(item.children){
            item.children = that.recursiveFilter(item.children)
          }
          return item
        })
        return data
      },
      trimSpace(array) {
        for (let i = 0; i < array.length; i++) {
          if (array[i] == "" || array[i] == null || typeof (array[i]) == "undefined") {
            array.splice(i, 1);
            i = i - 1;
          }
        }
        return array;
      },
      removeStr(val,str){
        let value ='';
        for (let i = 0; i < val.length; i++) {
          if(val[i]!=str){
            value += val[i];
          }
        }
        return value;
      },
    },
    model: { prop: 'value', event: 'change' },
  }
</script>

<style lang="less" scoped>
  .j-area-linkage {
    height:40px;
    /deep/ .area-cascader-wrap .area-select {
      width: 100%;
    }

    /deep/ .area-select .area-selected-trigger {
      line-height: 1.15;
    }
  }

</style>